# import os
# import sys

# import yaml
# from yaml import FullLoader

# from fastapi import FastAPI, File, UploadFile, HTTPException
# from fastapi.responses import FileResponse

# from src.parser.md_parser import md2html
# from src.provider.docx_processor import DocxProcessor

# config: dict = {
#     "version": "0.1.0"
# }

# app = FastAPI()

# # 创建临时文件夹
# temp_dir = "temp"
# os.makedirs(temp_dir, exist_ok=True)

# # 生成资源文件目录访问路径
# def resource_path(relative_path):
#     if getattr(sys, 'frozen', False):  # 是否Bundle Resource
#         base_path = sys._MEIPASS
#     else:
#         base_path = os.path.abspath(".")
#     return os.path.join(base_path, relative_path)


# @app.post("/convert/")
# async def convert_markdown_to_docx(input_file: UploadFile = File(...), 
#                                    output_file: str = "output.docx", 
#                                    style_file: str = "./config/default_style.yaml"):
#     docx_path = output_file if output_file else input_file.filename + ".docx"

#     # 将上传的 Markdown 文件保存到临时文件中
#     temp_markdown_path = os.path.join("./temp/", input_file.filename)
#     with open(temp_markdown_path, "wb") as buffer:
#         buffer.write(await input_file.read())

#     # 转换 Markdown 到 HTML
#     md2html(temp_markdown_path, temp_markdown_path + ".html")

#     # 读取样式配置文件
#     if not os.path.exists(style_file):
#         style_file = resource_path(os.path.join("src/config/default_style.yaml"))
#     with open(style_file, "r", encoding="utf-8") as file:
#         conf = yaml.load(file, FullLoader)

#     # 将 HTML 转换为 Docx
#     DocxProcessor(style_conf=conf).html2docx(temp_markdown_path + ".html", docx_path)

#     # 删除临时文件
#     # os.remove(temp_markdown_path)
#     # os.remove(temp_markdown_path + ".html")

#     return FileResponse(docx_path, media_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document', filename=output_file)

import os
import sys
import tempfile

import yaml
from yaml import FullLoader

from fastapi import FastAPI, File, UploadFile
from fastapi.responses import FileResponse

from src.parser.md_parser import md2html
from src.provider.docx_processor import DocxProcessor
from starlette.middleware.cors import CORSMiddleware

config: dict = {
    "version": "0.1.0"
}

app = FastAPI()

# 允许所有域进行跨源请求，您可以根据需要调整这些参数
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有源
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有方法
    allow_headers=["*"],  # 允许所有头
)

# 创建临时文件夹
temp_dir = os.path.join(os.getcwd(), "temp")
os.makedirs(temp_dir, exist_ok=True)

# 定义样式文件路径
style_file = "/raid/users/zq/markdocx-master/src/config/default_style.yaml"


# 生成资源文件目录访问路径
def resource_path(relative_path):
    if getattr(sys, 'frozen', False):  # 是否Bundle Resource
        base_path = sys._MEIPASS
    else:
        base_path = os.path.abspath(".")
    return os.path.normpath(os.path.join(base_path, relative_path))


@app.post("/convert/")
async def convert_markdown_to_docx(input_file: UploadFile = File(...),
                                   output_file: str = "output.docx"):
    docx_path = output_file if output_file else input_file.filename + ".docx"

    # 生成唯一的临时文件名
    temp_markdown_fd, temp_markdown_path = tempfile.mkstemp(suffix=".md", dir=temp_dir)

    os.close(temp_markdown_fd)

    # Remove the temporary Markdown file
    os.remove(temp_markdown_path)

    # 将上传的 Markdown 文件保存到临时文件中
    with open(temp_markdown_path, "wb") as buffer:
        buffer.write(await input_file.read())

    # 转换 Markdown 到 HTML
    md2html(temp_markdown_path, temp_markdown_path + ".html")

    # 读取样式配置文件
    # if not os.path.exists(style_file):
    #     style_file_path = resource_path(style_file)
    # else:
    style_file_path = style_file
    with open(style_file_path, "r", encoding="utf-8") as file:
        conf = yaml.load(file, FullLoader)

    # 将 HTML 转换为 Docx
    DocxProcessor(style_conf=conf).html2docx(temp_markdown_path + ".html", docx_path)

    # 删除临时文件
    os.remove(temp_markdown_path)
    os.remove(temp_markdown_path + ".html")

    return FileResponse(docx_path, media_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document', filename=output_file)
